package cn.huaqingcheng.tianshu.core.auth.jwt;

import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

@SuppressWarnings("SpellCheckingInspection")
class ECKeyPersistence {

    public static void generateAndSaveKeys(Path privateKey, Path publicKey) throws Exception {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
        keyGen.initialize(new ECGenParameterSpec("secp256r1"), new SecureRandom());
        KeyPair keyPair = keyGen.generateKeyPair();

        PrivateKey privKey = keyPair.getPrivate();
        PublicKey pubKey = keyPair.getPublic();

        try (OutputStream fos = Files.newOutputStream(privateKey)) {
            fos.write(privKey.getEncoded());
        }
        try (OutputStream fos = Files.newOutputStream(publicKey)) {
            fos.write(pubKey.getEncoded());
        }
    }

    public static KeyPair loadKeys(Path privateKeyFile, Path publicKeyFile) throws Exception {
        byte[] privBytes = Files.readAllBytes(privateKeyFile);
        PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privBytes);
        KeyFactory kf = KeyFactory.getInstance("EC");
        ECPrivateKey privKey = (ECPrivateKey) kf.generatePrivate(privSpec);

        byte[] pubBytes = Files.readAllBytes(publicKeyFile);
        X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubBytes);
        ECPublicKey pubKey = (ECPublicKey) kf.generatePublic(pubSpec);

        return new KeyPair(pubKey, privKey);
    }

}
